package com.ext.aic.handler;

import static android.app.Service.START_STICKY;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;

import androidx.core.app.NotificationCompat;

import com.ext.aic.R;
import com.ext.aic.builder.ForegroundServiceBuilder;

public class ForegroundServiceHandler {

    private ForegroundServiceBuilder foregroundServiceBuilder;

    public int onStartCommand() {
        return START_STICKY;
    }

    @SuppressLint("ForegroundServiceType")
    public <S extends Service> void onCreate(S service, ForegroundServiceBuilder builder) {
        this.foregroundServiceBuilder = builder;
        createNotificationChannel(service);
        service.startForeground(builder.getNotificationId(), buildPersistentNotification(service));
    }

    private Notification buildPersistentNotification(Context context) {
        return new NotificationCompat.Builder(context, foregroundServiceBuilder.getChannelId())
                .setContentTitle(foregroundServiceBuilder.getForegroundNotifyTitle())
                .setContentText(foregroundServiceBuilder.getForegroundNotifyDesc())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setOngoing(true)
                .build();
    }

    private <S extends Service> void createNotificationChannel(S service) {
        NotificationChannel channel = new NotificationChannel(
                foregroundServiceBuilder.getChannelId(),
                foregroundServiceBuilder.getChannelName(),
                NotificationManager.IMPORTANCE_LOW
        );
        channel.setDescription(foregroundServiceBuilder.getChannelDescription());
        NotificationManager manager = service.getSystemService(NotificationManager.class);
        if (manager != null) {
            manager.createNotificationChannel(channel);
        }
    }
}
